package org.monkeyk.demo.security.spring;

import org.monkeyk.security.SecurityHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * @author Shengzhao Li
 */
public class SpringSecurityHolder implements SecurityHolder<UserDetails> {

    private static Logger logger = LoggerFactory.getLogger(SpringSecurityHolder.class);

    @Override
    public UserDetails currentPrincipal() {
        SecurityContext context = SecurityContextHolder.getContext();
        if (context == null) {
            logger.debug("Current SecurityContext is null");
            return null;
        }
        Authentication authentication = context.getAuthentication();
        if (authentication == null) {
            logger.debug("Current Authentication is null");
            return null;
        }
        Object principal = authentication.getPrincipal();
        if (principal instanceof UserDetails) {
            return (UserDetails) principal;
        }
        logger.debug("Expect current Principal is an UserDetails instance, but it is {0}, return null", principal);
        return null;
    }
}
